const path = require('path')
const xlsx = require('xlsx')
var fs = require('fs')
function convertExcelFileToJsonUsingXlsx() {
  const file = xlsx.readFile('./language_doc/language.xlsx')
  const tempData = xlsx.utils.sheet_to_json(file.Sheets[file.SheetNames[0]])
  delete tempData[0].key
  let lanObj = {} //所有语言对象
  for (let key in tempData[0]) {
    lanObj[key] = {}
  }
  // Skip header row which is the colum names
  tempData.shift()
  for (let key in lanObj) {
    tempData.forEach((rowItem) => {
      if (rowItem.key) {
        if (rowItem[key] !== '') {
          lanObj[key][rowItem.key] = rowItem[key]
        } else {
          lanObj[key][rowItem.key] = null
        }
      }
    })
  }
  // call a function to save the data in a json file
  generateJSONFile(lanObj)
}

function generateJSONFile(data) {
  try {
    for (let key in data) {
      let file = path.join(__dirname, '../locales', `${key}.json`)
      fs.writeFile(file, JSON.stringify(data[key]), function (err) {
        if (err) {
          return console.log(err)
        }
        //console.log('文件创建成功，地址：' + file)
      })
    }
  } catch (err) {
    console.error(err)
  }
}
convertExcelFileToJsonUsingXlsx()
